package org.shopen.ai.puremvc.model.algo.dls
{
	import org.shopen.ai.puremvc.model.algo.FailureResult;
	import org.shopen.ai.puremvc.model.algo.ISearchAlgo;
	import org.shopen.ai.puremvc.model.algo.ISearchNode;
	import org.shopen.ai.puremvc.model.algo.ISearchProblem;
	import org.shopen.ai.puremvc.model.algo.ISearchResult;

	public class DepthLimitedSearchAlgo implements ISearchAlgo
	{
		protected var limit : int = 1;
		
		[Bindable]
		private var _title : String = "Depth Limited Search";
		[Bindable]
		public function get title() : String
		{
			return this._title;
		}
		public function set title(value : String) : void
		{
			this._title = value;
		}
		
		public function DepthLimitedSearchAlgo(limit : int)
		{
			this.limit = limit;
		}

		public function toString():String
		{
			return "Depth Limited Search"
		}
		
		public function search(problem:ISearchProblem) : ISearchResult
		{
			return recursiveSearch(problem.intialNode, problem, limit);
		}
		
		protected function recursiveSearch(node : ISearchNode, problem : ISearchProblem, limit : int) : ISearchResult
		{
			var cutoffOccurred : Boolean = false;
			var result : ISearchResult;
			if (problem.isGoal(node))
			{
				return node;
			}
			else if (node.depth == limit)
			{
				return new CutOffResult();
			}
			else
			{
				for each(var successor : ISearchNode in problem.expand(node))
				{
					result = recursiveSearch(successor, problem, limit);
					if (result is CutOffResult)
					{
						cutoffOccurred = true;
					}
					else if (!(result is FailureResult))
					{
						return result;
					}
				}
				if (cutoffOccurred)
				{
					return new CutOffResult();
				}
				else
				{
					return new FailureResult();
				}
			}
		}
		
	}
}